package com.chenl.consumer.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class TimeoutTask extends TimerTask {
    private volatile boolean canceled = false;
    private final HttpServletResponse httpResponse;

    public TimeoutTask(HttpServletResponse httpResponse) {
        this.httpResponse = httpResponse;
    }

    public void cancelTask() {
        this.canceled = true;
    }

    @Override
    public void run() {
        if (!canceled) {
            // 中断请求并返回超时错误信息
            httpResponse.setStatus(500);
            httpResponse.setContentType("text/plain;charset=UTF-8");
            try {
                httpResponse.getWriter().println("Request timeout.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Timer timer = new Timer();
        TimeoutTask timeoutTask = new TimeoutTask(response); // 设置处理超时时间为10秒
        timer.schedule(timeoutTask, 10000);

        // 后续处理request请求

        timer.cancel(); // 取消定时器
        timeoutTask.cancelTask(); // 取消任务
    }
}


